package com._54programer.demo.packet.ok;

import java.nio.charset.Charset;

import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	ctxHandler.ctx = ctx;
        //给客户端发送10条数据
        for(int i=0; i<10; i++){
            String msg = "Hello server!!!";
            byte[] content = msg.getBytes(Charset.forName("utf-8"));
            int len = content.length;
            //创建协议包
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(len);
            messageProtocol.setContent(content);
            System.err.println(JSON.toJSON(messageProtocol));
            ctxHandler.ctx.writeAndFlush(messageProtocol);
        }
        
        
        
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
//    	String msg = "Hello server!!!";
//        byte[] content = msg.getBytes(Charset.forName("utf-8"));
//        int len = content.length;
//        //创建协议包
//        MessageProtocol messageProtocol = new MessageProtocol();
//        messageProtocol.setLen(len);
//        messageProtocol.setContent(content);
//    	ctxHandler.ctx.writeAndFlush(messageProtocol);
    }
    
    
}
